<template>
  <div class="encryption-tools">
    <ToolContainer
      tool-name="加密工具"
      title="专业加密解密工具"
      description="支持MD5、SHA系列、Base64、AES等多种加密算法，保护您的数据安全"
      :header-icon="Lock"
      icon-color="#F56C6C"
      default-tab="md5"
      @tab-change="handleTabChange"
    >
      <template #tabs>
        <!-- MD5加密标签页 -->
        <el-tab-pane label="MD5加密" name="md5">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="encrypt-section">
                <el-form label-width="100px">
                  <el-form-item label="输入内容">
                    <el-input
                      v-model="md5Input"
                      type="textarea"
                      :rows="6"
                      placeholder="请输入需要加密的内容..."
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleMd5Encrypt"
                :loading="loading"
                :disabled="!md5Input.trim()"
              >
                MD5加密
              </el-button>
              <el-button 
                @click="clearInput('md5')"
                :disabled="!md5Input.trim()"
              >
                清空
              </el-button>
            </template>

            <template #result>
              <div v-if="md5Output" class="result-display">
                <h4>加密结果：</h4>
                <el-input
                  v-model="md5Output"
                  type="textarea"
                  :rows="4"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyResult('md5')">
                    复制结果
                  </el-button>
                  <el-button @click="clearOutput('md5')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- SHA系列标签页 -->
        <el-tab-pane label="SHA系列" name="sha">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="sha-section">
                <el-form label-width="100px">
                  <el-form-item label="输入内容">
                    <el-input
                      v-model="shaInput"
                      type="textarea"
                      :rows="6"
                      placeholder="请输入需要加密的内容..."
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleSha1Encrypt"
                :loading="loading"
                :disabled="!shaInput.trim()"
              >
                SHA1加密
              </el-button>
              <el-button 
                type="success" 
                @click="handleSha256Encrypt"
                :loading="loading"
                :disabled="!shaInput.trim()"
              >
                SHA256加密
              </el-button>
              <el-button 
                type="warning" 
                @click="handleSha512Encrypt"
                :loading="loading"
                :disabled="!shaInput.trim()"
              >
                SHA512加密
              </el-button>
            </template>

            <template #result>
              <div v-if="shaOutput" class="result-display">
                <h4>加密结果：</h4>
                <el-input
                  v-model="shaOutput"
                  type="textarea"
                  :rows="4"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyResult('sha')">
                    复制结果
                  </el-button>
                  <el-button @click="clearOutput('sha')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- Base64编码标签页 -->
        <el-tab-pane label="Base64编码" name="base64">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="base64-section">
                <el-form label-width="100px">
                  <el-form-item label="输入内容">
                    <el-input
                      v-model="base64Input"
                      type="textarea"
                      :rows="6"
                      placeholder="请输入需要编码/解码的内容..."
                    />
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleBase64Encode"
                :loading="loading"
                :disabled="!base64Input.trim()"
              >
                Base64编码
              </el-button>
              <el-button 
                type="success" 
                @click="handleBase64Decode"
                :loading="loading"
                :disabled="!base64Input.trim()"
              >
                Base64解码
              </el-button>
            </template>

            <template #result>
              <div v-if="base64Output" class="result-display">
                <h4>编码/解码结果：</h4>
                <el-input
                  v-model="base64Output"
                  type="textarea"
                  :rows="4"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyResult('base64')">
                    复制结果
                  </el-button>
                  <el-button @click="clearOutput('base64')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>

        <!-- AES加密标签页 -->
        <el-tab-pane label="AES加密" name="aes">
          <ToolSection
            :show-upload="false"
            :show-progress="false"
          >
            <template #options>
              <div class="aes-section">
                <el-form label-width="100px">
                  <el-form-item label="输入内容">
                    <el-input
                      v-model="aesInput"
                      type="textarea"
                      :rows="4"
                      placeholder="请输入需要加密/解密的内容..."
                    />
                  </el-form-item>
                  <el-form-item label="密钥">
                    <el-input
                      v-model="aesKey"
                      placeholder="请输入密钥（16/24/32位）"
                      show-password
                    />
                  </el-form-item>
                  <el-form-item label="偏移量">
                    <el-input
                      v-model="aesIv"
                      placeholder="请输入偏移量（16位，CBC模式需要）"
                    />
                  </el-form-item>
                  <el-form-item label="加密模式">
                    <el-radio-group v-model="aesMode">
                      <el-radio label="ECB">ECB</el-radio>
                      <el-radio label="CBC">CBC</el-radio>
                      <el-radio label="CFB">CFB</el-radio>
                      <el-radio label="OFB">OFB</el-radio>
                      <el-radio label="CTR">CTR</el-radio>
                    </el-radio-group>
                  </el-form-item>
                </el-form>
              </div>
            </template>

            <template #actions>
              <el-button 
                type="primary" 
                @click="handleAesEncrypt"
                :loading="loading"
                :disabled="!aesInput.trim() || !aesKey.trim()"
              >
                AES加密
              </el-button>
              <el-button 
                type="success" 
                @click="handleAesDecrypt"
                :loading="loading"
                :disabled="!aesInput.trim() || !aesKey.trim()"
              >
                AES解密
              </el-button>
              <el-button @click="generateKey">
                生成密钥
              </el-button>
            </template>

            <template #result>
              <div v-if="aesOutput" class="result-display">
                <h4>加密/解密结果：</h4>
                <el-input
                  v-model="aesOutput"
                  type="textarea"
                  :rows="4"
                  readonly
                />
                <div class="result-actions">
                  <el-button type="success" @click="copyResult('aes')">
                    复制结果
                  </el-button>
                  <el-button @click="clearOutput('aes')">
                    清空结果
                  </el-button>
                </div>
              </div>
            </template>
          </ToolSection>
        </el-tab-pane>
      </template>
    </ToolContainer>

    <!-- 功能介绍组件 -->
    <FeatureIntro
      :title="featureConfig.title"
      :description="featureConfig.description"
      :header-icon="featureConfig.headerIcon"
      :features="featureConfig.features"
      :initial-visible="showIntro"
      @close="showIntro = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { Lock } from '@element-plus/icons-vue'
import CryptoJS from 'crypto-js'
import ToolContainer from '@/components/ToolContainer.vue'
import ToolSection from '@/components/ToolSection.vue'
import FeatureIntro from '@/components/FeatureIntro.vue'
import { featuresConfig } from '@/config/featuresConfig.js'

// 基础数据
const loading = ref(false)
const showIntro = ref(true)
const featureConfig = featuresConfig.encryptionTools

// MD5相关
const md5Input = ref('')
const md5Output = ref('')

// SHA相关
const shaInput = ref('')
const shaOutput = ref('')

// Base64相关
const base64Input = ref('')
const base64Output = ref('')

// AES相关
const aesInput = ref('')
const aesKey = ref('')
const aesIv = ref('')
const aesMode = ref('ECB')
const aesOutput = ref('')

// 事件处理
function handleTabChange(tabName: string) {
  console.log('切换到标签页:', tabName)
}

// MD5加密
function handleMd5Encrypt() {
  if (!md5Input.value.trim()) {
    ElMessage.warning('请输入需要加密的内容')
    return
  }
  loading.value = true
  setTimeout(() => {
    try {
      md5Output.value = CryptoJS.MD5(md5Input.value).toString()
      ElMessage.success('MD5加密完成')
    } catch (error) {
      ElMessage.error('加密失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

// SHA系列加密
function handleSha1Encrypt() {
  if (!shaInput.value.trim()) {
    ElMessage.warning('请输入需要加密的内容')
    return
  }
  loading.value = true
  setTimeout(() => {
    try {
      shaOutput.value = CryptoJS.SHA1(shaInput.value).toString()
      ElMessage.success('SHA1加密完成')
    } catch (error) {
      ElMessage.error('加密失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

function handleSha256Encrypt() {
  if (!shaInput.value.trim()) {
    ElMessage.warning('请输入需要加密的内容')
    return
  }
  loading.value = true
  setTimeout(() => {
    try {
      shaOutput.value = CryptoJS.SHA256(shaInput.value).toString()
      ElMessage.success('SHA256加密完成')
    } catch (error) {
      ElMessage.error('加密失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

function handleSha512Encrypt() {
  if (!shaInput.value.trim()) {
    ElMessage.warning('请输入需要加密的内容')
    return
  }
  loading.value = true
  setTimeout(() => {
    try {
      shaOutput.value = CryptoJS.SHA512(shaInput.value).toString()
      ElMessage.success('SHA512加密完成')
    } catch (error) {
      ElMessage.error('加密失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

// Base64编码解码
function handleBase64Encode() {
  if (!base64Input.value.trim()) {
    ElMessage.warning('请输入需要编码的内容')
    return
  }
  loading.value = true
  setTimeout(() => {
    try {
      base64Output.value = btoa(unescape(encodeURIComponent(base64Input.value)))
      ElMessage.success('Base64编码完成')
    } catch (error) {
      ElMessage.error('编码失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

function handleBase64Decode() {
  if (!base64Input.value.trim()) {
    ElMessage.warning('请输入需要解码的内容')
    return
  }
  loading.value = true
  setTimeout(() => {
    try {
      base64Output.value = decodeURIComponent(escape(atob(base64Input.value)))
      ElMessage.success('Base64解码完成')
    } catch (error) {
      ElMessage.error('解码失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

// AES加密解密
function handleAesEncrypt() {
  if (!aesInput.value.trim()) {
    ElMessage.warning('请输入需要加密的内容')
    return
  }
  if (!aesKey.value.trim()) {
    ElMessage.warning('请输入密钥')
    return
  }
  
  loading.value = true
  setTimeout(() => {
    try {
      let encrypted
      const key = CryptoJS.enc.Utf8.parse(aesKey.value)
      
      if (aesMode.value === 'ECB') {
        encrypted = CryptoJS.AES.encrypt(aesInput.value, key, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
        })
      } else {
        if (!aesIv.value.trim()) {
          ElMessage.warning('CBC模式需要输入偏移量')
          loading.value = false
          return
        }
        const iv = CryptoJS.enc.Utf8.parse(aesIv.value)
        encrypted = CryptoJS.AES.encrypt(aesInput.value, key, {
          iv: iv,
          mode: CryptoJS.mode[aesMode.value],
          padding: CryptoJS.pad.Pkcs7
        })
      }
      
      aesOutput.value = encrypted.toString()
      ElMessage.success('AES加密完成')
    } catch (error) {
      ElMessage.error('加密失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

function handleAesDecrypt() {
  if (!aesInput.value.trim()) {
    ElMessage.warning('请输入需要解密的内容')
    return
  }
  if (!aesKey.value.trim()) {
    ElMessage.warning('请输入密钥')
    return
  }
  
  loading.value = true
  setTimeout(() => {
    try {
      let decrypted
      const key = CryptoJS.enc.Utf8.parse(aesKey.value)
      
      if (aesMode.value === 'ECB') {
        decrypted = CryptoJS.AES.decrypt(aesInput.value, key, {
          mode: CryptoJS.mode.ECB,
          padding: CryptoJS.pad.Pkcs7
        })
      } else {
        if (!aesIv.value.trim()) {
          ElMessage.warning('CBC模式需要输入偏移量')
          loading.value = false
          return
        }
        const iv = CryptoJS.enc.Utf8.parse(aesIv.value)
        decrypted = CryptoJS.AES.decrypt(aesInput.value, key, {
          iv: iv,
          mode: CryptoJS.mode[aesMode.value],
          padding: CryptoJS.pad.Pkcs7
        })
      }
      
      aesOutput.value = decrypted.toString(CryptoJS.enc.Utf8)
      ElMessage.success('AES解密完成')
    } catch (error) {
      ElMessage.error('解密失败：' + error.message)
    } finally {
      loading.value = false
    }
  }, 300)
}

// 生成随机密钥
function generateKey() {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
  let key = ''
  for (let i = 0; i < 16; i++) {
    key += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  aesKey.value = key
  
  // 生成IV
  let iv = ''
  for (let i = 0; i < 16; i++) {
    iv += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  aesIv.value = iv
  
  ElMessage.success('已生成随机密钥和偏移量')
}

// 工具函数
function clearInput(type: string) {
  switch (type) {
    case 'md5':
      md5Input.value = ''
      break
    case 'sha':
      shaInput.value = ''
      break
    case 'base64':
      base64Input.value = ''
      break
    case 'aes':
      aesInput.value = ''
      aesKey.value = ''
      aesIv.value = ''
      break
  }
  ElMessage.info('已清空输入')
}

function clearOutput(type: string) {
  switch (type) {
    case 'md5':
      md5Output.value = ''
      break
    case 'sha':
      shaOutput.value = ''
      break
    case 'base64':
      base64Output.value = ''
      break
    case 'aes':
      aesOutput.value = ''
      break
  }
  ElMessage.info('已清空结果')
}

function copyResult(type: string) {
  let text = ''
  switch (type) {
    case 'md5':
      text = md5Output.value
      break
    case 'sha':
      text = shaOutput.value
      break
    case 'base64':
      text = base64Output.value
      break
    case 'aes':
      text = aesOutput.value
      break
  }
  
  if (text) {
    navigator.clipboard.writeText(text)
    ElMessage.success('结果已复制到剪贴板')
  } else {
    ElMessage.warning('没有可复制的内容')
  }
}
</script>

<style scoped>
.encryption-tools {
  position: relative;
}

.encrypt-section,
.sha-section,
.base64-section,
.aes-section {
  width: 100%;
}

.result-display {
  width: 100%;
}

.result-display h4 {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: var(--el-text-color-primary, #303133);
}

.result-actions {
  margin-top: 16px;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .result-actions {
    flex-direction: column;
  }
}
</style> 